package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.mybatis.service.impl.CoolServiceImpl;
import cn.da.shuai.cool.system.service.mapper.CoolLoginLogMapper;
import cn.da.shuai.cool.system.model.entity.log.CoolLoginLog;
import cn.da.shuai.cool.system.service.service.ICoolLoginLogService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 系统访问日志服务实现类
 */
@Service
public class CoolLoginLogServiceImpl extends CoolServiceImpl<CoolLoginLogMapper, CoolLoginLog> implements ICoolLoginLogService {

    @Override
    public void insertLoginLog(CoolLoginLog loginLog) {
        this.save(loginLog);
    }

    @Override
    public List<CoolLoginLog> selectLoginLogList(CoolLoginLog loginLog) {
        return this.list(getWrapper(loginLog));
    }

    @Override
    public Page<CoolLoginLog> selectLoginLogPage(CoolLoginLog loginLog, Page<CoolLoginLog> page) {
        return this.page(page, getWrapper(loginLog));
    }

    @Override
    public int deleteLoginLogByIds(Long[] infoIds) {
        return this.removeByIds(Arrays.asList(infoIds)) ? infoIds.length : 0;
    }

    @Override
    public void cleanLoginLog() {
        this.remove(new LambdaQueryWrapper<>());
    }

    private LambdaQueryWrapper<CoolLoginLog> getWrapper(CoolLoginLog loginLog) {
        LambdaQueryWrapper<CoolLoginLog> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(loginLog.getIpaddr()), CoolLoginLog::getIpaddr, loginLog.getIpaddr())
           .eq(StrUtil.isNotBlank(loginLog.getStatus()), CoolLoginLog::getStatus, loginLog.getStatus())
           .like(StrUtil.isNotBlank(loginLog.getLoginName()), CoolLoginLog::getLoginName, loginLog.getLoginName())
           .between(loginLog.getCreateTime() != null && loginLog.getUpdateTime() != null,
                   CoolLoginLog::getLoginTime, loginLog.getCreateTime(), loginLog.getUpdateTime());
        return lqw;
    }
}